package leetcode.每日一题;

import org.junit.Test;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2021/8/20 21:22
 * @description：https://leetcode-cn.com/problems/reverse-string-ii/
 */
public class 反转字符串II {
    @Test
    public void test() {
        Solution solution = new Solution();
        System.out.println(solution.reverseStr("abcdefg", 8));
    }

    class Solution {
        public String reverseStr(String s, int k) {
            StringBuilder builder = new StringBuilder();
            StringBuilder sub = new StringBuilder();
            int i = 0;
            for (; i < s.length(); i++) {
                int factor = i / k;
                if (factor % 2 == 0) {
                    sub.append(s.charAt(i));
                    if ((i + 1) % k == 0) {
                        builder.append(sub.reverse());
                        sub = new StringBuilder();
                    }
                } else {
                    sub.append(s.charAt(i));
                    if ((i + 1) % k == 0) {
                        builder.append(sub);
                        sub = new StringBuilder();
                    }
                }
            }
            if ((i / k) % 2 == 0) {
                builder.append(sub.reverse());
            } else builder.append(sub);
            return builder.toString();
        }
    }
}
